<?php
namespace Pay\Service\Qqpay;

use Pay\Service\Qqpay\ActionAbstract;

class App extends ActionAbstract
{

    /*
     * 如果没有参数config默认取自有的配置
     */
    public function __construct($config = false)
    {
        parent::__construct($config);
    }

    /*
     * 进行H5支付
     * 一些必要参数$params如下:
     * $params['price']:价格
     * $params['body']:支付信息
     * $params['orderNumber']:订单编号
     */
    public function doApp($params)
    {
        if (!$params['body']) {
            return false;
        }
        if (!$params['price'] || !$params['orderNumber']) {
            return false;
        }
        $nonceStr = \Pay\Service\Common\Randstr::human(16);
        $ip = \Pay\Service\Common\Ip::getClientIp();
        $param = [
            'appid' => $this->config['appId'],
            'mch_id' => $this->config['mchId'],
            'nonce_str'=> $nonceStr,
            'body'=> $params['body'],
            'fee_type' => 'CNY',
            'out_trade_no' => $params['orderNumber'],
            'total_fee'=> $params['price'],
            'spbill_create_ip' => $ip,
            'notify_url' => $this->config['notifyUrl'],
            'trade_type'=> 'APP',
        ];
        ksort($param);
        $str = '';
        foreach ($param as $key => $value) {
            $str .= $key.'='.$value.'&';
        }
        $signStr = $str.'key='.$this->config['key'];
        $sign = strtoupper(md5($signStr));
        $param['sign'] = $sign;
        $content = $this->arrayToXml($param);
        $ret['payUrl'] = $this->doPay($content);
        $ret['appId'] = $this->config['appId'];
        return $ret;
    }

    protected function doPay($data)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_TIMEOUT, 30000);
        curl_setopt($curl, CURLOPT_URL, $this->config['payUrl']);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        $res = curl_exec($curl);
        curl_close($curl);
        $ret = $this->xmlToArray($res);
        return $ret['return_code'] == 'SUCCESS' ? $ret['prepay_id'] : '';
    }
}
?>
